#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import time
import re
import logging
import math
import sendPEmail

import urllib2
import myCEXFunctions

emailMessager = sendPEmail.PEmail()
logging.basicConfig(format='%(asctime)s; %(message)s', filename='trade.log',level=logging.DEBUG)
myCexFunc = myCEXFunctions.function()
demo = myCexFunc.getcexapi('credentials.txt','hannesh')



btcZero=0
showWechsel=True
btc_avl=0
medBidAsk=0
messageSent=False
initialMessage2Send=False

while True:
    try:        
        bal = demo.balance()  
        ghs_avl=myCexFunc.getFromBal(bal,'GHS','available')
        ghs_orders=myCexFunc.getFromBal(bal,'GHS','orders')
        btc_avl_old=btc_avl
        btc_avl=myCexFunc.getFromBal(bal,'BTC','available')
        btc_orders=myCexFunc.getFromBal(bal,'BTC','orders')
        
        ticker = demo.ticker()
        medBidAsk_old=medBidAsk        
        medBidAsk=(float(ticker['bid'])+float(ticker['ask']))/2 
        
         
        
        realBidAsk=0.00675
        
          
        if btc_avl>btc_avl_old or abs(medBidAsk_old-medBidAsk)>0.00005:
            myCexFunc.printStatus(ghs_avl,medBidAsk,btc_avl,realBidAsk,btc_orders)            
            
            
        if showWechsel:
            if btc_orders<0.500: 
                btcZero += 1
                if btcZero>1:
                    btcZero=-6                    
                    if not messageSent:
                        emailMessager.sendMessage('btc_orders smaller than 0.500 btc. suggest have a look@CEX')
                        messageSent=True     
                else:
                    print "immer noch btc_orders",btc_orders
                    btcZero=0
            else:
                btcZero=0
                #print "btc_orders=",btc_orders
            
        
        
        if initialMessage2Send:
           emailMessager.sendMessage('Test email, to check initially emailOK')
           initialMessage2Send=False                
        time.sleep(30)   
    except:
        print "General Exception"    
        #raise 
        btcZero=0        
        time.sleep(60)
    